package com.mla.fastdfs.filter;

import com.github.pagehelper.util.StringUtil;
import com.mla.fastdfs.commom.RedisConstant;
import com.mla.fastdfs.pojo.User;
import com.mla.fastdfs.utils.HttpUtil;
import com.mla.fastdfs.utils.RedisUtil;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter extends FormAuthenticationFilter {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private FilterHandle filterHandle;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpUtil.setHeader(httpRequest, httpResponse);

        if ("OPTIONS".equals(httpRequest.getMethod()) || filterHandle.filterPath(httpRequest.getRequestURI())) {
            return true;
        }

        String aToken = httpRequest.getParameter("aToken");
        if (StringUtil.isEmpty(aToken)) {
            return false;
        }

        User user = (User) redisUtil.hget(RedisConstant.LOGINUSER, aToken);
        if (user == null) {
            httpResponse.sendRedirect("/common/overdue");
            return false;
        }
        return true;
    }
}
